# == Schema Information
#
# Table name: admin_users
#
#  id              :bigint(8)        not null, primary key
#  name            :string(255)
#  password_digest :string(255)
#  status          :integer
#  login           :string(255)
#  created_at      :datetime         not null
#  updated_at      :datetime         not null
#  email           :string(255)      default("test@admin.com")
#  role_id         :bigint(8)
#

class AdminUser < ApplicationRecord
  # belongs_to :role
  has_many :role_assignments, dependent: :destroy
  # 通过assign获取用户所有角色（关联表）
  has_many :roles, through: :role_assignments

  attr_accessor :role
  # 一个用户只有一个角色
  # delegate :computed_permissions, to: :role
  #
  # 配置Gavatar
  include Gravtastic
  gravtastic
  # 配置paper_trail，用于追踪修改
  has_paper_trail only: [:login, :name,:email, :password_digest, :password_confirmation,:status]

  # 配置验证规则
  validates :name, presence: true
  validates :password, confirmation: true, length: { minimum: 6 }, allow_blank: true
  validates_uniqueness_of :login

  # 配置密码哈希摘要
  has_secure_password validations: false


  # 配置AR的枚举类型
  enum status: {active: 1, forbidden: 0}
  default_value_for :status,1

  # check permission n2n
  def computed_permissions
    roles.map(&:computed_permissions).reduce(RoleCore::ComputedPermissions.new, &:concat)
  end


  def roles_names
    str = ""
    self.roles.each do |role|``
      str+=role.name+" "
    end
    str
  end


  scope :sorted, -> { order(created_at: :desc) }

end
